package org.smart.framework.core.prox;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * @author lyric
 * @version 1.0.0
 * @date 2017/2/11 22:42
 * @description 切面代理
 */
public class AspectProxy implements Proxy {

    private static final Logger logger = LoggerFactory.getLogger(AspectProxy.class);

    /**
     * @param proxyChain 代理链
     * @return
     * @throws Throwable
     * @author lyric
     * @description 执行链式代理
     */
    @Override
    public Object doProxy(ProxyChain proxyChain) throws Throwable {
        Object result = null;

        Class<?> cls = proxyChain.getTargetClass();
        Method method = proxyChain.getTargetMethod();
        Object[] params = proxyChain.getMethodParams();

        begin();
        try {
            if (intercept(cls, method, params)) {
                if (intercept(cls, method, params)) {
                    before(cls, method, params);
                    result = proxyChain.doProxyChain();
                    after(cls, method, params, result);
                } else {
                    result = proxyChain.doProxyChain();
                }
            }
        } catch (Exception e) {
            logger.error("proxy failure", e);
            error(cls, method, params, e);
            throw e;
        } finally {
            end();
        }
        return result;
    }

    /**
     * @author lyric
     * @description 开始
     */
    public void begin() {
    }

    /**
     * @author lyric
     * @description 执行拦截
     * @param cls 目标类
     * @param method 目标方法
     * @param params 方法参数
     * @return
     * @throws Throwable
     */
    public boolean intercept(Class<?> cls, Method method, Object[] params) throws Throwable {
        return true;
    }

    /**
     * @author lyric
     * @description 前置增强
     * @param cls 目标类
     * @param method 目标方法
     * @param params 方法参数
     * @throws Throwable
     */
    public void before(Class<?> cls, Method method, Object[] params) throws Throwable {
    }

    /**
     * @author lyric
     * @description 后置增强
     * @param cls 目标类
     * @param method 目标方法
     * @param params 方法参数
     * @param result 拦截结果
     * @throws Throwable
     */
    public void after(Class<?> cls, Method method, Object[] params, Object result) throws Throwable {
    }

    /**
     * @author lyric
     * @description 拦截异常
     * @param cls 目标类
     * @param method 目标方法
     * @param params 方法参数
     * @param e
     */
    public void error(Class<?> cls, Method method, Object[] params, Throwable e) {
    }

    /**
     * @author lyric
     * @description 结束
     */
    public void end() {
    }
}
